<script setup lang='ts'>
import { useGetCascade } from '@fl/api/add-elevator-api'
import { useFailEdit } from '@fl/api/elevator-api/verify'
import type { cascadeParam } from '@fl/api/add-elevator-api/model/apply-model'
import type { historyEditParam } from '@fl/api/add-elevator-api/model/history-model'
// import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import type { PlusColumn } from 'plus-pro-components'

const props = withDefaults(defineProps<{
    data?: any
}>(), {
    data: () => {},
})
const { data } = toRefs(props)
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })
const formRef = ref()
const title = ref<string>('修改')
const isLoading = ref<boolean>(false)

const initialState = {
    areaCode: '',
    areaName: '',
    streetCode: '',
    streetName: '',
    communityCode: '',
    communityName: '',
    projectId: '',
    projectName: '',
    buildingId: '',
    building: '',
    unitId: '',
    unit: '',
    num: undefined,
    remark: '',
}
const state = ref<historyEditParam>(cloneDeep(initialState))

// 级联选择
const initialParams = {
    targetLabel: '',
    areaCode: '',
    streetCode: '',
    communityCode: '',
    projectName: '',
    building: '',
    unit: '',
    time: undefined, // 刷新用，每次选择后都调用接口
}
const areaParams = ref<cascadeParam>(cloneDeep(initialParams))
const streetParams = ref<cascadeParam>(cloneDeep(initialParams))
const communityParams = ref<cascadeParam>(cloneDeep(initialParams))
const projectParams = ref<cascadeParam>(cloneDeep(initialParams))
const buildingParams = ref<cascadeParam>(cloneDeep(initialParams))
const unitParams = ref<cascadeParam>(cloneDeep(initialParams))

areaParams.value.targetLabel = 'area'

// 详情
function getApplyShow() {
    state.value = cloneDeep(data.value)
    // console.log('state.value', state.value)
    // 查街道
    streetParams.value.targetLabel = 'street'
    streetParams.value.areaCode = state.value.areaCode
    // 查社区
    communityParams.value.targetLabel = 'community'
    communityParams.value.streetCode = state.value.streetCode
    // 查小区
    projectParams.value.targetLabel = 'project'
    projectParams.value.communityCode = state.value.communityCode
    // 查栋
    buildingParams.value.targetLabel = 'building'
    buildingParams.value.projectId = state.value.projectId
    // 查单元
    unitParams.value.targetLabel = 'unit'
    unitParams.value.building = state.value.building
}

watch(() => visible.value, () => {
    if (visible.value) {
        getApplyShow()
    } else {
        reset()
    }
})

watch(() => state.value.unit, (val) => {
    const unit = String(val)
    // 允许输入“无”和英文、数字
    const regex = /^[a-zA-Z0-9]+$/;
    if (!regex.test(unit)) {
        console.log('unit', unit)
        state.value.unit = unit.replace(/[^a-zA-Z0-9无]/g, '');
    }
    // 输入纯数字是时，限制200
    const regexNum = /^[0-9]+$/;
    if (regexNum.test(unit) && Number(unit) >= 200) {
        state.value.unit = '200'
    }
})

// 下拉框：过滤数据
const areaOptions = ref<any>([])
const streetOptions = ref<any>([])
const communityOptions = ref<any>([])
const projectOptions = ref<any>([])
const buildingOptions = ref<any>([])
const unitOptions = ref<any>([])
const finalUnitOptions = computed(() =>{
    const originArr: any = [{ label: '无', value: '无'}]
    for (var i = 1; i <= 200; i++) {
        originArr.push({ label: String(i), value: String(i) })
    }
    // console.log('前端数据', originArr)
    // 后端返的列表数据，替换value
    const tempArr = toRaw(unitOptions.value)
    const finalArr = originArr.reduce((pre, cur) => {
        for (var i = 0; i < tempArr.length; i++) {
            if(cur.label === tempArr[i].label) {
                cur.value = tempArr[i].value
            }
        }
        pre.push(cur)
        return pre
    }, [])
    return finalArr
})

const { data: areaList } = useGetCascade(areaParams)
const { data: streetList } = useGetCascade(streetParams)
const { data: communityList } = useGetCascade(communityParams)
const { data: projectList } = useGetCascade(projectParams)
const { data: buildingList } = useGetCascade(buildingParams)
const { data: unitList } = useGetCascade(unitParams)

watchEffect(() => {
    if (areaList.value) {
        areaOptions.value = cloneDeep(areaList.value)
    }
    if (streetList.value) {
        streetOptions.value = cloneDeep(streetList.value)
    }
    if (communityList.value) {
        communityOptions.value = cloneDeep(communityList.value)
    }
    if (projectList.value) {
        projectOptions.value = cloneDeep(projectList.value)
    }
    if (buildingList.value) {
        buildingOptions.value = cloneDeep(buildingList.value)
    }
    if (unitList.value) {
        unitOptions.value = cloneDeep(unitList.value)
    }
})

// 清空街道
function clearStreet() {
    state.value.streetCode = ''
    state.value.streetName = ''
    clearCommunity()
}

// 清空社区
function clearCommunity() {
    state.value.communityCode = ''
    state.value.communityName = ''
    clearProject()
}

// 清空小区
function clearProject() {
    state.value.projectId = ''
    state.value.projectName = ''
    clearBuilding()
}

// 清空栋
function clearBuilding() {
    state.value.buildingId = ''
    state.value.building = ''
    clearUnit()
}

// 清空单元
function clearUnit() {
    state.value.unitId = ''
    state.value.unit = ''
    unitOptions.value = []
}

// 1.选择区
function areaChange() {
    //清空
    state.value.streetCode = ''
    state.value.communityCode = ''
    clearStreet()

    const target = areaOptions.value.find((v: any) => v.value === state.value.areaCode)
    state.value.areaName = target.label
    streetParams.value.targetLabel = 'street'
    streetParams.value.areaCode = state.value.areaCode
    streetParams.value.time = new Date().getTime()
    // console.log('streetParams.value', streetParams.value)
}

// 2.街道选择
function streetChange() {
    //清空
    state.value.communityCode = ''
    clearCommunity()

    const target = streetOptions.value.find((v: any) => v.value === state.value.streetCode)
    state.value.streetName = target.label
    communityParams.value.targetLabel = 'community'
    communityParams.value.streetCode = state.value.streetCode
    communityParams.value.time = new Date().getTime()
    console.log('communityParams.value', communityParams.value, target)
}

// 3.社区选择
function communityChange() {
    //清空
    state.value.projectId = ''
    clearProject()

    const target = communityOptions.value.find((v: any) => v.value === state.value.communityCode)
    state.value.communityName = target.label
    projectParams.value.targetLabel = 'project'
    projectParams.value.communityCode = state.value.communityCode
    projectParams.value.time = new Date().getTime()
    // console.log('projectParams.value', streetParams.value)
}

// 4.小区选择
function projectChange() {
    //清空
    state.value.building = ''
    clearBuilding()
    
    const target = projectOptions.value.find((v: any) => v.value === state.value.projectId)
    state.value.projectName = target.label
    buildingParams.value.targetLabel = 'building'
    buildingParams.value.projectId = state.value.projectId
    buildingParams.value.time = new Date().getTime()

    // console.log('projectParams.value', streetParams.value)
}

// 5.栋选择
function buildingChange() {
    const target = buildingOptions.value.find((v: any) => v.label === state.value.building)
    state.value.buildingId = target?.value || ''
    unitParams.value.targetLabel = 'unit'
    unitParams.value.building = state.value.building
    unitParams.value.time = new Date().getTime()
    //清空
    clearUnit()
}

// 6.单元选择

// 提交表单
const { isPending, mutate } = useFailEdit()

// 提交
async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (!valid) {
        ElMessage.warning('请填写完整表单')
        return
    }
    const params = {
        id: id.value ?? '',
        ...unref(state),
        areaCode: state.value.areaCode || null, // 后端要求传null
        streetCode: state.value.streetCode || null,
        communityCode: state.value.communityCode || null,
        projectId: state.value.projectId || null,
        unitId: (!state.value.unitId || state.value.unitId === '无') ? null : state.value.unitId,
        remark: state.value.remark || ''
    }
    // console.log('params', params)
    mutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            cancel()
        },
    })
}

function cancel() {
    visible.value = false
    reset()
}

function reset() {
    id.value = ''
    state.value = cloneDeep(initialState)
    formRef.value?.formInstance.resetFields()
}

const columns: PlusColumn[] = [
    {
        label: '所在区',
        prop: 'areaCode',
    },
    {
        label: '街道',
        prop: 'streetCode',
    },
    {
        label: '社区',
        prop: 'communityCode',
    },
    {
        label: '小区',
        prop: 'projectId',
    },
    {
        label: '栋',
        prop: 'building',
    },
    {
        label: '单元楼',
        prop: 'unit',
    },
    {
        fieldProps: {
            autosize: { maxRows: 5, minRows: 4 },
        },
        label: '备注',
        prop: 'remark',
        valueType: 'textarea',
    },
]

const rules = computed(() => ({
    areaCode: [
        {
            message: '请选择所在区',
            required: true,
        },
    ],
    streetCode: [
        {
            message: '请选择街道',
            required: true

        },
    ],
    communityCode: [
        {
            message: '请选择社区',
            required: true

        },
    ],
    projectId: [
        {
            message: '请选择小区',
            required: true
        },
    ],
    building: [
        {
            message: '栋',
            required: true,
        },
    ],
    unit: [
        {
            message: '单元楼',
            required: true,
        },
    ],
}))

</script>

<template>
    <el-drawer v-model="visible" :size="600">
        <template #header>
            <div class="font-600 text-black text-24">
                {{ title }}
            </div>
        </template>
        <ElSkeleton v-if="isLoading" animated class="mt-20" />

        <template v-else>
            <div class="mt-20 plusform">
                <PlusForm ref="formRef" v-model="state" :columns="columns" :label-width="120" :rules="rules"
                    :has-footer="false" :row-props="{ gutter: 20 }">

                    <template #plus-field-areaCode>
                        <el-select v-model="state.areaCode" placeholder="请选择" filterable @change="areaChange">
                            <el-option v-for="item in areaOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </template>

                    <template #plus-field-streetCode>
                        <el-select v-model="state.streetCode" placeholder="请选择" filterable @change="streetChange">
                            <el-option v-for="item in streetOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </template>

                    <template #plus-field-communityCode>
                        <el-select v-model="state.communityCode" placeholder="请选择" filterable @change="communityChange">
                            <el-option v-for="item in communityOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </template>

                    <template #plus-field-projectId>
                        <el-select v-model="state.projectId" placeholder="请选择" filterable @change="projectChange">
                            <el-option v-for="item in projectOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </template>

                    <template #plus-field-building>
                        <!-- :disabled="isBuildingDisabeld" -->
                        <el-select v-model="state.building" filterable clearable allow-create default-first-option :reserve-keyword="false" placeholder="请选择/输入" @change="buildingChange">
                            <el-option v-for="item in buildingOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </template>

                    <template #plus-field-unit>
                        <!-- :disabled="isUnitDisabeld" -->
                        <el-select v-model="state.unit" filterable clearable allow-create default-first-option
                            :reserve-keyword="false" placeholder="请选择/输入">
                            <el-option v-for="item in finalUnitOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>

                    </template>

                </plusform>
            </div>

        </template>

        <template #footer>
            <div class="flex">
                <el-button type="primary" class="w-[50%]" :loading="isPending" @click="submit">
                    提交
                </el-button>

                <el-button class="w-[50%]" @click="cancel">
                    取消
                </el-button>
            </div>
        </template>
    </el-drawer>

</template>

<style lang="scss" scoped>
.plusform {
    // height: 640px;
    overflow-y: auto;
    overflow-x: hidden;
}

.positive {
    position: absolute;
    width: 100%;
    max-height: 110px;
    background: #fff;
    z-index: 10;
    top: 34px;
    left: 0;
    overflow-y: auto;
    border: 1px solid #eee;
    border-radius: 4px;

    .item {
        padding-left: 10px;
        cursor: pointer;
    }

    .item:hover {
        background: #eee;
    }
}

.title {
    font-size: 16px;
    font-weight: 600;
    height: 60px;
    line-height: 60px;
}
</style>
